from google.appengine.ext import webapp 
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler 
from google.appengine.ext.webapp.util import run_wsgi_app
import logging, email, model
from google.appengine.api import mail
from google.appengine.api import users
import sync

def email_notify(email_address, subject, message):
    '''
    send an email
    '''
    mail.send_mail(sender=users.get_current_user().email(),
              to=email_address,
              subject=subject,
              body=message)
    logging.info('Email is sent to %s : %s' % (email_address, message))
    
    
class EmailHandler(InboundMailHandler):
    def receive(self, message):
        e = model.Email()
        for fld in ['subject', 'sender', 'date', 'to', 'cc']:
            if hasattr(message, fld):
                setattr(e, fld, getattr(message, fld))
        
        plaintext_bodies = message.bodies('text/plain')
        html_bodies = message.bodies('text/html')
        htmls = []
        for content_type, body in html_bodies:
            htmls.append(body.decode())
        logging.info(htmls)
        e.html_content = '\n'.join(htmls)
        htmls = []
        for content_type, body in plaintext_bodies:
            htmls.append(body.decode())
        e.plaintext_content = '\n'.join(htmls) 
        e.put()
        logging.info("Received a message from:%s  to: %s" % (message.sender, message.to))
        to_email = message.to
        #trigger the sync functions to each table
        logging.info('sync iform triggered by email: %s' % to_email)
        if to_email=='compaction_test@dlzfusion.appspot.com':
            #sync the compaction_test table
            sm = sync.SyncManager('compaction_test', to_email)
            sm.sync()
            sync.populate_project_info('compaction_test', 'compaction_form')
        elif to_email=='compaction_form@dlzfusion.appspot.com':
            sm = sync.SyncManager('compaction_form', to_email)
            sm.sync()
            sync.populate_project_info('compaction_test', 'compaction_form')
        elif to_email=='asphalt_test@dlzfusion.appspot.com':
            sm = sync.SyncManager('asphalt_test', to_email)
            sm.sync()
            sync.populate_project_info('asphalt_test', 'asphalt_form')
        elif to_email=='asphalt_form@dlzfusion.appspot.com':
            sm = sync.SyncManager('asphalt_form', to_email)
            sm.sync()
            sync.populate_project_info('asphalt_test', 'asphalt_form')
        else:
            logging.info('Not a known email: %s' % to_email)
            sync.sync_all()
        